<?php

namespace app\modules\api\models;

use yii;
use yii\db\Query;
use app\lib\Redis;

class AdminUser
{
    use Redis;

    private $table;
    private $redis;

    public function __construct()
    {
        $this->table = yii::$app->db->tablePrefix . 'adminuser';
        $this->redis = $this->getInstance();
    }

    /**
     * @param $name string 用户名
     * @param $password string 密码
     * @return array|bool
     */
    public function getUser($name, $password)
    {
        $key = 'all_users';
        $users = $this->redis->hgetall($key);
        foreach ($users as $v) {
            $arr = json_decode($v, true);
            if (($arr['name'] == $name) && ($arr['password'] == $password)) {
                return $arr;
            }
        }

        $db = new Query();
        $info = $db->select('*')->from($this->table)->where(['name' => $name, 'password' => $password])->one();
        if ($info) {
            $this->redis->hset($key, $info['id'], json_encode($info));
            return $info;
        }

        return false;
    }
}